<?php
/**
 * Created by PhpStorm.
 * User: fengdh
 * Date: 2019/8/20
 * Time: 15:08
 */

namespace console\controllers\platform;

use business\company\services\DeveloperService;
use business\elasticsearch\models\DeveloperModel;
use common\cache\CacheManager;
use common\utils\DateTimeUtils;
use console\controllers\BaseIndexController;
use search\models\DisabledDeveloperModel;

class DeveloperIndexController extends BaseIndexController
{
    public function actionFull()
    {
        $developer_service = new DeveloperService();
        $developer_ids = $developer_service->getDeveloperIdsList();
        if (empty($developer_ids)) {
            echo '没有找到开发商';
            return;
        }

        $this->handDeveloperData($developer_ids);
    }

    public function actionIncrement()
    {
        //1.获取上次查询的时间点
        $timestamp = CacheManager::get(BaseIndexController::LATEST_PLATFORM_DEVELOPER_QUERY_TIME_KEY);
        $now = DateTimeUtils::time();
        if (empty($timestamp)) {
            $timestamp = strtotime('-' . BaseIndexController::DEFAULT_INCREMENT_TIME . ' minutes', $now);
        }
        $last_query_time = date('Y-m-d H:i:s', $timestamp);
        \Yii::info("elasticsearch increment time of platform developer index update is " . $last_query_time);
        $developer_service = new DeveloperService();
        $developer_ids = $developer_service->getDeveloperIdsList($last_query_time);
        CacheManager::set(BaseIndexController::LATEST_PLATFORM_DEVELOPER_QUERY_TIME_KEY, $now, 0);
        if (empty($developer_ids)) {
            echo '没有找到开发商';
            return;
        }
        $this->handDeveloperData($developer_ids);
    }

    private function handDeveloperData($developer_ids)
    {
        $developer_count = count($developer_ids);
        $loop_count = intval($developer_count / $this->_every_time_number) + 1;
        echo '总数: ' . $loop_count . PHP_EOL;
        echo '正在进行: ';
        for ($i = 0; $i < $loop_count; $i++) {
            echo $i . ' ';
            for ($j = $i * $this->_every_time_number; $j < ($i + 1) * $this->_every_time_number && $j < $developer_count; $j++) {
                $developer_id = $developer_ids[$j];
                $developer_info = [];
                try {
                    $developer_info = $this->getDetailDeveloperInfo($developer_id);
                    $developer_es_model = DeveloperModel::findOne($developer_id);

                    //校验条件
                    $checkResult = $this->checkConstructIndexCondition($developer_id, $developer_info);
                    if (!$checkResult['success']) {
                        if ($developer_es_model) {
                            $developer_es_model->deleteAll(['_id'=>$developer_id]);

                            //@todo 删除搜索引擎中开发商发布的招标招募信息

                        }
                        continue;
                    }
                    if (empty($developer_es_model)) {
                        $developer_es_model = new DeveloperModel();
                        $developer_es_model->primaryKey = $developer_id;
                    }
                    $developer_es_model->setAttributes($developer_info, false);
                    $developer_es_model->indexCreatedTime = date('Y-m-d H:i:s');
                    $rs = $developer_es_model->save();
                    if (!$rs) {
                        \Yii::error('update es_developer failed! developer_id:' . $developer_id);
                    }
                } catch (\Exception $e) {
                    $title = isset($developer_info['developerName']) ? $developer_info['developerName'] : '';
                    $this->saveUnIndexData('es_developer', $title, $developer_id, $e);
                }
            }
        }
    }

    /**
     * 根据developerId获取该开发商索引所需的所有信息
     * @param $developer_id
     * @return array
     */
    private function getDetailDeveloperInfo($developer_id)
    {
        $developer_service = new DeveloperService();

        //1.获取基础信息
        $basicInfo = $developer_service->getDeveloperBasicInfo($developer_id);

        //2.获取开发商招标招募统计总数
        $statisticInfo = $developer_service->getDeveloperStatisticInfo($developer_id);

        //3.开发商项目信息
        $projectsInfo = $developer_service->getDeveloperProjectsInfo($developer_id);

        return array_merge($basicInfo, $statisticInfo, $projectsInfo);
    }

    /**
     * 检查索引构建的条件
     * @param $developerId
     * @param $developerInfo
     * @return array
     */
    private function checkConstructIndexCondition($developerId, $developerInfo)
    {
        $result = [
            'success' => true,
            'errMsg' => ''
        ];

        //开发商name为测试数据
        if ($result['success'] &&
            ((!isset($developerInfo['developerName']) || !strncmp($developerInfo['developerName'], 'test_', 5)) ||
                (isset($developerInfo['shortName']) && !strncmp($developerInfo['shortName'], 'test_', 5)) || ((int)$developerInfo['state'] != 2))
        ) {
            $result['errMsg'] = "此开发商($developerId)为测试数据，数据不会导入搜索引擎！";
            $result['success'] = false;
        }
        $data = DisabledDeveloperModel::findOne(['developer_id'=>$developerId,'is_disabled'=>1]);
        if ($result['success'] && !empty($data)) {
            $result['errMsg'] = "此开发商($developerId)被禁止搜索，数据不会导入搜索引擎！";
            $result['success'] = false;
        }
        //非合规性数据持久化
        if (!$result['success']) {
            $title = isset($developerInfo['developerName']) ? $developerInfo['developerName'] : '';
            $this->saveUnIndexData('es_developer', $title, $developerId, $result['errMsg']);
        }

        return $result;
    }

}